package st.business.tepth.business.user.busnumber.workholder.maintain.pass;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import st.business.tepth.R;
import st.business.tepth.R2;
import st.business.tepth.base.OnItemChooseListener;
import st.business.tepth.business.bean.MaintainPassInfoBean;
import st.business.tepth.business.bean.PersonBean;
import st.business.tepth.business.businfo.BusInfoDelegate;
import st.business.tepth.business.event.ReloadBusNumberDataEvent;
import st.business.tepth.business.event.ReloadMaintainWorkDataEvent;
import st.business.tepth.business.event.StartBrotherEvent;
import st.business.tepth.business.user.busnumber.workholder.dialog.DialogContactWorker;
import st.business.tepth.business.user.busnumber.workholder.maintain.finish.DialogFinishNotPass;
import st.business.tepth.config.ItemFields;
import st.business.tepth.manager.UserManager;
import st.shadow.library.core.base.mvp.MvpFragment;
import st.shadow.library.ui.dialog.DialogLoader;
import st.shadow.library.ui.dialog.IDialogClickListener;
import st.shadow.library.ui.recycler.BaseDecoration;
import st.shadow.library.ui.recycler.MultipleItemEntity;

/**
 * @author zhangyu
 * @date 2019/4/19
 */
public class MaintainPassDelegate extends MvpFragment<MaintainPassPresenter>
        implements MaintainPassContract.View {
    public static MaintainPassDelegate newInstance(int id,
                                                   int type,
                                                   int operationState) {
        Bundle bundle = new Bundle();
        bundle.putInt("id", id);
        bundle.putInt("type", type);
        bundle.putInt("operationState", operationState);
        MaintainPassDelegate delegate = new MaintainPassDelegate();
        delegate.setArguments(bundle);
        return delegate;
    }

    @BindView(R2.id.recycler_view_tab)
    RecyclerView mRecyclerViewClassification;
    @BindView(R2.id.tv_work_type)
    TextView mTvType;
    @BindView(R2.id.view_pager)
    ViewPager mViewPager;
    @BindView(R2.id.tv_check_pass)
    TextView mTvCheckPass;
    @BindView(R2.id.tv_check_not_pass)
    TextView mTvNotPass;
    @BindView(R2.id.tv_cancel_work)
    TextView mTvCancelWork;
    private ClassificationAdapter mClassificationAdapter;
    private int mType;
    private int mRepairId;
    private DialogLoader mDialogLoader;
    private int mOperationState;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mRepairId = bundle.getInt("id");
            mType = bundle.getInt("type");
            mOperationState = bundle.getInt("operationState");
        }
    }

    @Override
    public MaintainPassPresenter getPresenter() {
        return new MaintainPassPresenter(this);
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_maintain_work_pass;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        String type = "";
        switch (mType) {
            case 1:
                type = "小修";
                break;
            case 2:
                type = "一级保养";
                break;
            case 3:
                type = "二级保养";
                break;
            case 4:
                type = "三级保养";
                break;
            case 5:
                type = "电池保养";
                break;
        }
        mTvType.setText(String.format("%s--待过检", type));
        if (mOperationState == 0) {
            mTvCheckPass.setVisibility(View.GONE);
            mTvNotPass.setVisibility(View.GONE);
        } else {
            mTvCheckPass.setVisibility(View.VISIBLE);
            mTvNotPass.setVisibility(View.VISIBLE);
        }
        mRecyclerViewClassification.setLayoutManager(new LinearLayoutManager(_mActivity));
        mRecyclerViewClassification.addItemDecoration(
                BaseDecoration.create(_mActivity.getResources()
                        .getColor(R.color.fontColorWhite), 2));
        RecyclerView.ItemAnimator itemAnimator = mRecyclerViewClassification.getItemAnimator();
        if (itemAnimator != null) {
            itemAnimator.setChangeDuration(0);
        }
        mRecyclerViewClassification.setAdapter(mClassificationAdapter =
                new ClassificationAdapter(_mActivity,
                        R.layout.item_maintain_pass_classification,
                        null, new OnItemChooseListener<Integer>() {
                    @Override
                    public void onChoose(Integer position) {
                        chooseMaintain(position);
                    }
                }));
        mDialogLoader = new DialogLoader(_mActivity);
        mPresenter.getData(UserManager.getInstance().getToken(), mRepairId);
    }

    @Override
    public void showData(List<MultipleItemEntity> list) {
        mClassificationAdapter.setNewData(list);
        if (!list.isEmpty()) {
            chooseMaintain(0);
            mViewPager.setAdapter(new MaintainContentAdapter(getChildFragmentManager(),
                    list));
            //判断过检员是不是工单的作业人，如果是则按钮【取消作业完成】需要展示
            //如果不是则不需要展示该按钮
            boolean isWorker = false;
            for (MultipleItemEntity entity : list) {
                MaintainPassInfoBean infoBean = entity.getField(ItemFields.ITEM_OBJ);
                if (infoBean != null) {
                    List<PersonBean> workers = infoBean.getWorkerList();
                    if (workers != null) {
                        for (PersonBean personBean : workers) {
                            if (personBean.getJob_no().
                                    equals(UserManager.getInstance().getCurrentUserCode())) {
                                isWorker = true;
                                break;
                            }
                        }
                    }
                }
            }
            mTvCancelWork.setVisibility(isWorker ? View.VISIBLE : View.INVISIBLE);
        }
    }

    private void chooseMaintain(int position) {
        mViewPager.setCurrentItem(position);
    }

    @Override
    public void showError(String msg) {
        mDialogLoader.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void checkNotPassSucceed() {
        mDialogLoader.stopProgressWithSuccess("提交成功", null, new IDialogClickListener() {
            @Override
            public void onClick() {
                mDialogLoader.clearDialog();
                EventBus.getDefault().post(new ReloadMaintainWorkDataEvent(mRepairId));
            }
        });
    }

    @Override
    public void checkPassSucceed() {
        mDialogLoader.stopProgressWithSuccess("提交成功", null, new IDialogClickListener() {
            @Override
            public void onClick() {
                mDialogLoader.clearDialog();
                EventBus.getDefault().post(new ReloadBusNumberDataEvent());
            }
        });
    }

    @Override
    public void cancelWorkSucceed() {
        mDialogLoader.stopProgressWithSuccess("提交成功", null, new IDialogClickListener() {
            @Override
            public void onClick() {
                mDialogLoader.clearDialog();
                EventBus.getDefault().post(new ReloadBusNumberDataEvent());
            }
        });
    }

    @OnClick(R2.id.tv_check_not_pass)
    public void onNotPass() {
//        if (mClassificationAdapter != null && mClassificationAdapter.getCheckList() != null
//                && !mClassificationAdapter.getCheckList().isEmpty()) {
//            new DialogNotPassCheck(_mActivity, mClassificationAdapter.getCheckList(),
//                    new DialogNotPassCheck.OnConfirmListener() {
//                        @Override
//                        public void onConfirm(String classifications, String remark) {
//                            mDialogLoader.showProgressDialog(true, "正在提交", "请稍候...");
//                            mPresenter.checkNotPass(UserManager.getInstance().getToken(),
//                                    classifications, remark);
//                        }
//                    }).show();
//        } else {
//            ToastUtils.showShort("请先勾选分系");
//        }
        new DialogFinishNotPass(_mActivity, "过检不通过", mClassificationAdapter.getData(),
                new DialogFinishNotPass.OnConfirmListener() {
                    @Override
                    public void onConfirm(String ids, String reason) {
                        String[] listIds = ids.split(",");
                        List<DialogFinishNotPass.IDBean> idBeans = new ArrayList<>();
                        for (String id : listIds) {
                            idBeans.add(new DialogFinishNotPass
                                    .IDBean(Integer.parseInt(id)));
                        }
                        mDialogLoader.showProgressDialog(true, "正在提交", "请稍候...");
                        mPresenter.checkNotPass(UserManager.getInstance().getToken(),
                                JSON.toJSONString(idBeans), reason
                        );
                    }
                }).measureSize().show();
    }

    @OnClick(R2.id.tv_check_pass)
    public void onPass() {
//        if (mClassificationAdapter != null && mClassificationAdapter.getCheckList() != null
//                && !mClassificationAdapter.getCheckList().isEmpty()) {
//            mDialogLoader.showProgressDialog(true, "正在提交", "请稍候...");
//            mPresenter.checkPass(UserManager.getInstance().getToken(),
//                    mClassificationAdapter.getCheckIds());
//        } else {
//            ToastUtils.showShort("请先勾选分系");
//        }
        new DialogFinishNotPass(_mActivity, "过检通过", mClassificationAdapter.getData(),
                new DialogFinishNotPass.OnConfirmListener() {
                    @Override
                    public void onConfirm(String ids, String reason) {
                        String[] listIds = ids.split(",");
                        List<DialogFinishNotPass.IDBean> idBeans = new ArrayList<>();
                        for (String id : listIds) {
                            idBeans.add(new DialogFinishNotPass
                                    .IDBean(Integer.parseInt(id)));
                        }
                        mDialogLoader.showProgressDialog(true, "正在提交", "请稍候...");
                        mPresenter.checkPass(UserManager.getInstance().getToken(),
                                JSON.toJSONString(idBeans)
                        );
                    }
                }).measureSize().show();
    }

    @OnClick(R2.id.tv_bus_info)
    public void onShowBusInfo() {
        EventBus.getDefault().post(new StartBrotherEvent(BusInfoDelegate.newInstance(mRepairId)));
    }

    @OnClick(R2.id.tv_cancel_work)
    public void onWorkCancel() {
        mDialogLoader.showProgressDialog(false, "正在提交", "请稍候...");
        mPresenter.cancelFinishWork(UserManager.getInstance().getToken(),
                mRepairId);
    }

    @OnClick(R2.id.tv_contact_worker)
    public void onContactWorker() {
        new DialogContactWorker(_mActivity, mRepairId).show();
    }
}
